

//
//  RegisterVC.m
//  BusinessMarket
//
//  Created by Michael Li on 2018/11/9.
//  Copyright © 2018年 Michael Li. All rights reserved.
//

#import "RegisterVC.h"
#import "RightNaviItem.h"
#import "AKeyApplyVC.h"
@interface RegisterVC ()
@property (weak, nonatomic) IBOutlet UIButton *getMsgBtn;
@property (weak, nonatomic) IBOutlet UITextField *phoneNumTF;
@property (weak, nonatomic) IBOutlet UITextField *pswTF;
@property (weak, nonatomic) IBOutlet UITextField *getCodeTF;
@property(nonatomic,assign) int indexURL;
@property (weak, nonatomic) IBOutlet UIButton *clickRegisterBtn;
@property(nonatomic,strong) NSString *randomNumber;
@property(nonatomic,strong) AFHTTPSessionManager *manager;
@property(nonatomic,strong) NSDictionary *dict;
@property(nonatomic,strong) NSString *urlString;
@property (weak, nonatomic) IBOutlet UIButton *logInBtn;
@end

@implementation RegisterVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.manager = [AFHTTPSessionManager manager];
     self.navigationItem.rightBarButtonItem = [RightNaviItem initWithTitle:@"登录" style:UIBarButtonItemStylePlain target:self action:@selector(clickRightItem)];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.getMsgBtn.userInteractionEnabled = NO;
    [self.getMsgBtn setTitleColor:kLabel102Color forState:UIControlStateNormal];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(qingqiusuccess:) name:@"qingqiusuccess" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(qingqiusibai:) name:@"qingqiusibai" object:nil];
    self.logInBtn.layer.masksToBounds = YES;
    self.logInBtn.layer.cornerRadius = 6;
}
-(void)clickRightItem
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)qingqiusuccess:(NSNotification *)info
{
    NSString *message = [info.userInfo objectForKey:@"message"];
    [WSProgressHUD showImage:[UIImage imageNamed:@""] status:message];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [WSProgressHUD dismiss];
        [self.navigationController popViewControllerAnimated:YES];
    });
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
- (IBAction)phoneNumTF:(UITextField *)sender {
    if (sender.text.length >= 11) {
//        [sender resignFirstResponder];
        sender.text = [sender.text substringToIndex:11];
        self.getMsgBtn.userInteractionEnabled = YES;
        [self.getMsgBtn setTitleColor:kOrangeBg forState:UIControlStateNormal];
        //        //XLog(@"shoujiTF:%@----textField:%@",self.shoujiTF.text,textField.text);
    }else if (sender.text.length < 11) {
        self.getMsgBtn.userInteractionEnabled = NO;
        [self.getMsgBtn setTitleColor:kLabel102Color forState:UIControlStateNormal];
    }
}
- (IBAction)getCodeTF:(UITextField *)sender {
    
}
- (IBAction)newPSWTF:(UITextField *)sender {
}

- (IBAction)getMegBtn:(UIButton *)sender {
    if (![PhoneAndMailCheckObject phoneNumberIsTrue:self.phoneNumTF.text]) {
        [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"手机号码不正确,请重新输入"];
    }else {
        self.indexURL = 9;
        XLog(@"self.phoneNumTF.text:%@",self.phoneNumTF.text);
        [self openCountdown];
        self.dict = @{
                      @"phone": self.phoneNumTF.text,
                      };
        XLog(@"dict:%@",self.dict);
        self.urlString = [NSString stringWithFormat:@"%@/user/smsSend",kUrl];
        [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSString *message = [responseObject objectForKey:@"message"];
            [WSProgressHUD showImage:[UIImage imageNamed:@""] status:message];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }
}
#pragma mark-开启倒计时效果
-(void)openCountdown{
    
    int num = (arc4random() % 10000);
    self.randomNumber = [NSString stringWithFormat:@"%.4d", num];
    __block NSInteger time = 59; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.getMsgBtn setTitle:@"重新发送" forState:UIControlStateNormal];
                 [self.getMsgBtn setTitleColor:kOrangeBg forState:UIControlStateNormal];
                self.getMsgBtn.userInteractionEnabled = YES;
            });
            
        }else{
            
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                NSString *time = [NSString stringWithFormat:@"重新发送(%.2d)", seconds];
                [self.getMsgBtn setTitle:time forState:UIControlStateNormal];
                [self.getMsgBtn setTitleColor:kOrangeBg forState:UIControlStateNormal];
//                [self.getMsgBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
                self.getMsgBtn.userInteractionEnabled = NO;
            });
            time--;
        }
    });
    dispatch_resume(_timer);
}
- (IBAction)clickRegister:(UIButton *)sender {
    
    if (self.phoneNumTF.text.length<11) {
        [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"请输入手机号码"];
    }else if (![PhoneAndMailCheckObject phoneNumberIsTrue:self.phoneNumTF.text]) {
        [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"手机号码不正确,请重新输入"];
    }else if (self.getCodeTF.text.length == 0) {
        [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"请输入验证码"];
    }else if (self.pswTF.text.length == 0) {
        [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"请输入密码"];
    }else {
        self.indexURL = 8;
        self.dict = @{
                      @"password":self.pswTF.text,
                      @"phone": self.phoneNumTF.text,
                      @"code": self.getCodeTF.text
                      };
        XLog(@"dict:%@",self.dict);
        self.urlString = [NSString stringWithFormat:@"%@/user/register",kUrl];
        [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
             XLog(@"responseObject:%@",responseObject);
            NSString *message = [responseObject objectForKey:@"message"];
            NSInteger status = [[responseObject objectForKey:@"status"] integerValue];
            if (status == 200) {
                [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"注册成功,请登录"];
                NSDictionary *date = [responseObject objectForKey:@"date"];
                NSDictionary *user = [date objectForKey:@"user"];
                NSString *headImg = [user objectForKey:@"headimg"];
                NSString *uid = [user objectForKey:@"id"];
                NSString *phone = [user objectForKey:@"phone"];
                NSString *type = [user objectForKey:@"type"];
                NSString *nickname = [user objectForKey:@"nickname"];
                NSString *token = [date objectForKey:@"token"];
                [UserDefaultsHelper saveUid:@"" value:uid];
                [UserDefaultsHelper saveToken:@"" @"" value:token];
                [UserDefaultsHelper saveAutoLogIn:@"" value:@"YES"];
//                [self dismissViewControllerAnimated:YES completion:nil];
//                if (nickname.length != 0 &&headImg.length != 0) {
//                    [UserDefaultsHelper savePhoneHeadImg:@"" withHeadImgValue:headImg saveUid:@"" withUidValue:uid saveNickname:@"" withNicknameValue:nickname savePhone:@"" withPhone:phone saveType:@"" andType:type saveToken:@"" withTokenValue:token];
//                }else if (nickname.length == 0 &&headImg.length != 0) {
//                    [UserDefaultsHelper savePhoneNONickNameHeadImg:@"" withHeadImgValue:headImg saveUid:@"" withUidValue:uid savePhone:@"" withPhone:phone saveType:@"" andType:type saveToken:@"" withTokenValue:token];
//                }else if (nickname.length != 0 &&headImg.length == 0) {
//                    [UserDefaultsHelper savePhoneNOHeadImgUid:@"" withUidValue:uid saveNickname:@"" withNicknameValue:nickname savePhone:@"" withPhone:phone saveType:@"" andType:type saveToken:@"" withTokenValue:token];
//
//                }else {
//                    [UserDefaultsHelper saveType:@"" value:type];
//                    [UserDefaultsHelper saveIphone:@"" value:phone];
//                    [UserDefaultsHelper saveToken:@"" value:token];
//                    [UserDefaultsHelper saveUid:@"" value:uid];
//                }
                [self.navigationController popViewControllerAnimated:YES];
            }else {
                [WSProgressHUD showImage:[UIImage imageNamed:@""] status:message];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }
    
}
#pragma mark-代理:用户协议

- (IBAction)xieyi:(UIButton *)sender {
    AKeyApplyVC *vc = [[AKeyApplyVC alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}
@end
